define(['app','pagination','datetime','editor', 'filesaver', 'js/service/agupload','floatlayer'], function( app ) {
	'use strict'; 
	//报价管理
	app.controller('Delivery', function($scope, dataFactoryCRM, $q, crmConst, AgUpload) {
		//检索条件默认值
		$scope.customer       = '';
		$scope.salesPerson    = '';
		$scope.matter_key     = '888';
		$scope.matter_state   = '6';
		$scope.sessions_matter= '1';
		$scope.exportDefault  = -1;
		$scope.unit           = [{list:''}];
		$scope.status         = [{k: '0',v: '未处理'},{k: '1',v: '邮寄中'},{k: '2',v: '邮寄完成'},{k: '3',v: '被退回'},{k: '4',v: '挂起'}];
		$scope.sign_status     = [{k:'0',v:'未处理'},{k:'10',v:'签订完成'}];
		$scope.search         = {customer:'',sales:'',product:'',first_time:'',second_time:'',state:'5'};

		//分页默认值
		$scope.DeliveryPage = {pageAll: 1,pageNow: 1,pageSize:20,k: 3};

		$scope.busy = dataFactoryCRM.getDataByAPI('Delivery/communal').then(function(data) {
            $scope.today    = data.today;
            var arr = {};
            var address = window.location.href;
            arr = address.split("/");
            if(arr[6])   $scope.DeliveryList($scope.sessions_matter,$scope.matter_state,arr[6]);
            if($("#Contract-model").length==0) $scope.contractDetails = 1;  
        });	
		//首页 2354
		$scope.DeliveryList   = function(matter,matter_key,herf){
			if(herf !='' && herf !=undefined){
				if(herf==10)
					$("#add_css").addClass("selected");
				else
					$("#confirm_css").addClass("selected");
            	$("#remove_css").removeClass("selected");
            	matter_key = herf;
			}
        	if($scope.matter_state == '10'){
				$scope.hide_but = false;
				$scope.hide_but2 = true;
				$scope.hide_but3 = true;
			}else if($scope.matter_state == '20'){
				$scope.hide_but  = true;
				$scope.hide_but2 = false;
				$scope.hide_but3 = true;
			}else if($scope.matter_state == '30'){
				$scope.hide_but  = true;
				$scope.hide_but2 = true;
				$scope.hide_but3 = false; 
			}else {
				$scope.hide_but  = true;
				$scope.hide_but2 = true;
				$scope.hide_but3 = true;
			} 
			if( matter_key == 1 && matter == 6 ){
				$("#default").addClass("active");
				$("#invoice").removeClass("active");
				$("#refund").removeClass("active");
				$scope.firstsegment = 'active';
			}
			//单元内部查看方式
			if(!matter){
				$scope.sessions  = $scope.sessions_matter; 
				$scope.p         = $scope.DeliveryPage.pageNow;
			}else{
				$scope.sessions  = matter;	
				$scope.p         = 1;
			} 	
			
			if(matter_key && matter_key!=undefined) $scope.matter_state  = matter_key; 	
			else $scope.matter_state     = $scope.matter_state ;	

			//拷贝顶部tab状态锁定
			switch(matter)
			{	
				case 2:
					$scope.defaultcss = '';
					$scope.refund = '';
					$scope.invoice = 'active';
					break;
				case 3:
					$scope.defaultcss = '';
					$scope.refund = 'active';
					$scope.invoice = ''	;
					break;
				default:
					$scope.defaultcss = 'active';
					$scope.refund = '';
					$scope.invoice = '';
					break;
			}
			//拷贝检索tab状态锁定
			switch(matter_key)
			{
				case 10:
					$scope.selected10 = 'selected active';
					$scope.selected6 = '';
					$scope.selected20 = '';
					$scope.selected30 = '';
					$scope.selected40 = '';
					$scope.selected50 = '';
					break;
				case 20:
					$scope.selected10 = '';
					$scope.selected6 = '';
					$scope.selected20 = 'selected active';
					$scope.selected30 = '';
					$scope.selected40 = '';
					$scope.selected50 = '';
					break;
				case 30:
					$scope.selected10 = '';
					$scope.selected6 = '';
					$scope.selected20 = '';
					$scope.selected30 = 'selected active';
					$scope.selected40 = '';
					$scope.selected50 = '';
					break;
				case 40:
					$scope.selected10 = '';
					$scope.selected6 = '';
					$scope.selected20 = '';
					$scope.selected30 = '';
					$scope.selected40 = 'selected active';
					$scope.selected50 = '';
					break;
				case 50:
					$scope.selected10 = '';
					$scope.selected6 = '';
					$scope.selected20 = '';
					$scope.selected30 = '';
					$scope.selected40 = '';
					$scope.selected50 = 'selected active';
					break;
				default:
					$scope.selected10 = '';
					$scope.selected6 = 'selected active';
					$scope.selected20 = '';
					$scope.selected30 = '';
					$scope.selected40 = '';
					$scope.selected50 = '';
				break;
			}

			var listParam           = $scope.search;
	            listParam['psize']  = $scope.DeliveryPage.pageSize;
	            listParam['p']      = $scope.p ;
	            listParam['matter'] = $scope.sessions;
	            listParam['matter_key'] = $scope.matter_state; 
			var _url = 'Delivery/index?'+$.param( listParam );
			dataFactoryCRM.getDataByAPI(_url).then(function(data){
				if(data.rcode ){
					$scope.empty = true;
					$scope.unit  = data.data;
					$scope.DeliveryPage.pageSize = $scope.unit.psize;
					$scope.DeliveryPage.pageAll  = $scope.unit.page;
					$scope.DeliveryPage.pageNow  = $scope.unit.p;
					$scope.sessions_matter       =  $scope.sessions;
					$("#sessions_matter a ").val($scope.sessions_matter);
				}else{
					if($scope.unit.list != '')  $scope.unit.list = '';
					$scope.empty = false;
					$scope.DeliveryPage.pageAll = 0;
				}
			});
		}
		//初始化页面显示数据（如果是新弹出独立窗口则从父窗口获取）
	    window.loadClientCacheToScope($scope, function(){
	    	$scope.DeliveryList($scope.sessions_matter,$scope.matter_state,'');
	    });
		//查看状态
		$scope.state         = function(key){
			if(!key || key == undefined) $scope.matter_state = 6;
			else $scope.matter_state = key;
			$scope.DeliveryList($scope.sessions,$scope.matter_state);
		}
		//编辑合同邮寄
		$scope.EditorShow     = function(){
			$scope.verify_time = true;
			$("#sendTime").removeClass('error');

			$scope.initial = this.vlist;
			$scope.tel     = $scope.initial.phone; 
			$('#initialId').dropdown('set selected', $scope.initial.weigui_status);	
			//隐藏域赋值
			$("#deliveryId").val($scope.initial.delivery_id);
			$("#contractId").val($scope.initial.contract_id);

			if($scope.initial.delivery_num !="")  $scope.delivery_status = "邮寄中";
			else $scope.delivery_status = "待寄出";

			$('.ui.EditorShow').modal({
	          onApprove: function() {
	          	$("#delivery").val($scope.initial.delivery_id);
	            if( $('#frm-contract-mail').form('is valid') && $("#send_time").val() !=''){
	              	var _d = $('#frm-contract-mail').serialize();
					dataFactoryCRM.postDataByAPI("Delivery/deliveryEeditor",_d).then(function(data){
						if(data.rcode == 1){
							$('.ui.modal3').modal('show');
							$scope.Msg  = "编辑";
						}else{
							$('.ui.modal2').modal('show');
						}
						setTimeout(function() {
			                $('.time').modal('hide')
			            }, 3000)
            			$scope.DeliveryList($scope.sessions_matter,$scope.matter_state);
					})
	            }else{
	            	if($("#send_time").val() !='' ){
						$scope.verify_time = true;
					   	$("#sendTime").removeClass('error');
					}else{
						$scope.verify_time = false;
						$("#sendTime").addClass('error');
						return false;
					}
	                 return false;
	             }
	          }
	        }).modal('show');
		}
		//二次确认弹窗
		$scope.second_confirm = function(kId){
			$scope.secondId   = kId;
			$(".ui.second_confirm").modal('show');
		}
		//确认邮寄
		$scope.affirm          = function(Id){
			dataFactoryCRM.postDataByAPI("Delivery/confirm_editor",{delivery_id:Id}).then(function(data){
				if(data.rcode == 1){
					$('.ui.modal3').modal('show');
				}else{
					$('.ui.modal2').modal('show');
				}
				$scope.Msg  = "确认邮寄确认";
				setTimeout(function() {
	                $('.time').modal('hide')
	            }, 3000)
    			$scope.DeliveryList($scope.sessions_matter,$scope.matter_state);
			});
		}
		//批量操作
		$scope.confirm         = function(){
			$('.ui.confirm').modal({
	          onApprove: function() {
	          	var checkbox = []; 
				$('input[name="checkbox"]:checked').each(function(){ 
					checkbox.push($(this).val()); 
				});
				dataFactoryCRM.postDataByAPI("Delivery/confirm_editor",{batch:checkbox}).then(function(data){
					if(!data.failure){
						$('.ui.modal3').modal('show');
						$scope.Msg  = "编辑";
						setTimeout(function() {
			                $('.time').modal('hide')
			            }, 3000)
					}else{
						$('.ui.error_shw').modal('show');
					}
					$scope.DeliveryList($scope.sessions_matter,$scope.matter_state);
				});
	          }
	        }).modal('show');
	        var _url = "Delivery/confirm_show?status="+$scope.sessions + '&matter_state='+$scope.matter_state;
	        dataFactoryCRM.getDataByAPI(_url).then(function(data){
				$scope.confirmList = data.confirm;
			});
		}
		//导出邮寄记录
		$scope.export_delivery = function(key){
			$scope.search.first_time = '';
			$scope.search.second_tim = '';
			//路径
			var listParam           = $scope.search;
	            listParam['psize']  = $scope.DeliveryPage.pageSize;
	            listParam['p']      = $scope.DeliveryPage.pageNow;
	            listParam['matter'] = $scope.sessions;
	            listParam['matter_key'] = $scope.matter_key; 

	            if($scope.sessions == 1 && key != -1)          $scope.content = '合同邮寄数据记录表';
	            else if($scope.sessions == 1 && key == -1)     $scope.content = '导入合同邮寄记录标准模板';
	           	else if($scope.sessions == 2 && key != -1)     $scope.content = '发票邮寄数据记录表';
	           	else if($scope.sessions == 2 && key == -1)     $scope.content = '导入发票邮寄记录标准模板';
	           	else if($scope.sessions == 3 && key == -1)     $scope.content = '导入终止协议邮寄记录标准模板';
	           	else                              $scope.content = '终止协议邮寄数据记录表';
	        if(key == -1)
	        	var _url = 'Delivery/export_delivery?default='+key+'&matter='+$scope.sessions;
	        else
				var _url = 'Delivery/export_delivery?'+$.param( listParam );

			dataFactoryCRM.getDataByAPIS(_url).then(function(response) {
               var blob = new Blob([response], {
                    type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
                });
                saveAs(blob, $scope.content + '.xls');
                $scope.DeliveryList($scope.sessions_matter,$scope.matter_state);
            });
		}
		 //检测邮寄状态
	   	$scope.check_state     = function(){
	   		if($scope.initial.delivery_num != '') $scope.delivery_status = "邮寄中";
	   		else $scope.delivery_status = "待寄出";
	   	}		
		//导入邮寄记录
		$scope.import_delivery = function($fitem){
            AgUpload.add( $fitem );
            AgUpload.setUrl('Delivery/import_delivery?type='+$scope.sessions);
            AgUpload.param_add('action','upload');
            AgUpload.start().then( function( data ){
            	if(data.statistics){
            		$scope.statistics = data.statistics;
	            	$scope.failure    = data.failure;
	            	$('.ui.error_shw').modal('show');
            	}
            	$scope.DeliveryList($scope.sessions_matter,$scope.matter_state);
            });   
		}
		//点击邮寄完成操作
		$scope.completeShow    = function(){
			$("#frm-complete").form('clear');
			$scope.complete = this.vlist;
			$('.ui.complete').modal({
				observeChanges: true,
	          onApprove: function() {
          		if( $('#frm-complete').form('is valid')){
          		 	var url = "Delivery/complete?delivery_id="+$scope.complete.delivery_id +"&contract_id="+$scope.complete.contract_id+"&delivery_num="+$scope.complete.delivery_num+"&sign_status="+$scope.complete.sign_status+"&state="+$scope.complete.state;
	          	 	dataFactoryCRM.getDataByAPI(url).then(function(data){
						if(data.rcode == 1){
							$('.ui.modal3').modal('show');
						}else{
							$('.ui.modal2').modal('show');
						}
						$scope.Msg  = "邮寄完成编辑";
						setTimeout(function() {
			                $('.time').modal('hide')
			            }, 3000)
            			$scope.DeliveryList($scope.sessions_matter,$scope.matter_state);
					})
          		}else{
          			return  false;
          		}
	          }
	        }).modal('show');
		}
		//验证是否有重复运单号
		$scope.checkNum        = function(){
			var url = "Delivery/repeatCheck?delivery_num="+$scope.complete.delivery_num;
			dataFactoryCRM.getDataByAPI(url).then(function(data){
	       		$scope.results = data.checkResults;
	       		if($scope.results == 1 && $scope.complete.delivery_num !=""){
	       			$("#isExist").val('1');
	       		}else{
	       			$("#isExist").val('');
	       		}
			})
		}
		//取消提醒页面
		$scope.cancel_show     = function(cancelId){
			$scope.cancelId        = cancelId;
            $('.ui .cancel_show').modal('show');
		} 
		//邮寄取消
		$scope.cancel          = function(kId){
			dataFactoryCRM.getDataByAPI("Delivery/cancel?delivery_id=" + kId).then(function(data){
				if(data.rcode == 1){
					$('.ui.modal3').modal('show');
				}else{
					$('.ui.modal2').modal('show');
				}
				$scope.Msg  = "邮寄取消";
				setTimeout(function() {
	                $('.time').modal('hide')
	            }, 3000)
    			$scope.DeliveryList($scope.sessions_matter,$scope.matter_state);
			});
		}
		//时间检测
		$scope.check_time      = function(){
			if($("#send_time").val() !='' ){
				$scope.verify_time = true;
			   	$("#sendTime").removeClass('error');
			}else{
				$scope.isError      =true;
				$scope.verify_time = false;
				$("#sendTime").addClass('error');
				return false;
			}
		}	
	});
});